﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.JavaScript.JQuery;
using blackhouse.Web.FasterFiles;
using System.Globalization;
using blackhouse.BlackApart.Web;
using System.ComponentModel;
using blackhouse.BlackApart.Business;
using blackhouse.JavaScript;
using blackhouse.BlackApart.Business.Cities;
using blackhouse.BlackApart.Web.Navigation;

namespace blackhouse.Aparts.Web.Modules {
    public partial class OnlineReservation : System.Web.UI.UserControl {

        #region Fields

        private DateTime postArrivalDate = DateTime.MinValue;
        private DateTime postDepartureDate = DateTime.MinValue;
        private int postNumberOfPeople;
        private SearchState queryState = SearchState.GetFromContext();
        private int peoplesCount = 12;
        public event SearchValueChangedEventHandlers SeachValueChanged;

        #endregion

        #region Properties

        [Browsable(true)]
        [DefaultValue(12)]
        public int PeoplesCount {
            get { return this.peoplesCount; }
            set { this.peoplesCount = value; }
        }

        [Browsable(true)]
        [DefaultValue(0)]
        public int DisplayForApartmentId {
            get;
            set;
        }

        #endregion

        #region Event Handlers

        protected override void OnInit(EventArgs e) {
            HttpContext.Current.Items["DisableRollReservation"] = true;

            base.OnInit(e);

            this.lnkSubmit.Click += new EventHandler(lnkSubmit_Click);

            this.ReadParameters();
            if (Request["submitReservation"] == "1") {
                this.RedirectIfValid();
            }
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            this.AddJavaScript();
            this.PopulateControls();
        }

        protected void lnkSubmit_Click(object sender, EventArgs e) {
            if (SeachValueChanged != null) {
                this.RaiseValueChangedEvent();
            }
            else
                this.RedirectIfValid();
        }

        #endregion

        #region Methods

        public void ChangeButtonText(string text) {
            this.lnkSubmit.Text = text;
        }

        private void RaiseValueChangedEvent() {
            this.SeachValueChanged(this, new SearchChangedEventArgs(this.postArrivalDate, this.postDepartureDate, this.postNumberOfPeople));
        }

        private void PopulateControls() {
            this.ddlPeoplesCount.Items.Clear();
            for (int i = 1; i <= this.PeoplesCount; i++) {
                ListItem li = new ListItem(i.ToString());
                li.Selected = this.queryState.PeopleCount == i;
                this.ddlPeoplesCount.Items.Add(i.ToString());
            }

            this.ddlPeoplesCount.SelectedValue = this.queryState.PeopleCount.ToString();

            DateTime arrivalDate = DateTime.MinValue, departureDate = DateTime.MinValue, fallbackArrivalDate = DateTime.MinValue, fallbackDepartureDate = DateTime.MinValue;

            if (this.DisplayForApartmentId == 0) {
                fallbackArrivalDate = DateTime.Now;
                fallbackDepartureDate = fallbackArrivalDate.AddDays(1);
            }

            if (this.queryState.IsSet) {
                arrivalDate = this.queryState.ArrivalDate;
                departureDate = this.queryState.DepartureDate;
            }

            this.SetHiddenDateValue(this.arrivalDate, arrivalDate, fallbackArrivalDate);
            this.SetHiddenDateValue(this.departureDate, departureDate, fallbackDepartureDate);

            if (this.DisplayForApartmentId > 0) {
                this.PopulateForApartment(this.DisplayForApartmentId);
            }
            if (this.DisplayForApartmentId == 0)
                this.lnkSubmit.CssClass = this.lnkSubmit.CssClass + " wait-link";
        }

        private void PopulateForApartment(int apartmentId) {
            this.onlineReservation_ApartmentId.Value = this.DisplayForApartmentId.ToString();
            this.onlineReservation_ApartmentId.Visible = true;
            this.lblTitleExpanded.Visible = true;
            this.pnlReservationDescription.Visible = true;
            this.pnlLegend.Visible = true;
            this.pnlLoadingAvalibles.Visible = true;
            this.pnlUnavalibleApartment.Visible = true;
        }

        private void SetHiddenDateValue(HiddenField field, DateTime date, DateTime fallbackDate) {
            if (date == DateTime.MinValue && fallbackDate != DateTime.MinValue)
                date = fallbackDate;
            if (date != DateTime.MinValue)
                field.Value = date.ToString("dd.MM.yyyy");
        }

        private void AddJavaScript() {
            MultilanguageJsResource jsLang = new MultilanguageJsResource("/App_GlobalResources/ApartsJs.resx");

            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeJQueryUICulture(CultureInfo.CurrentCulture);
            jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.online-reservation.js,blackhouse.Aparts.Web");
            FasterFilesProvider ffp = new FasterFilesProvider();
            ffp.AddAfterScript("dateFormat = '" + CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern.Replace("MM", "M").Replace("yy", "y") + "';");
        }

        private void ReadParameters() {
            DateTime.TryParseExact(Request.Form[arrivalDate.UniqueID], "dd.MM.yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out this.postArrivalDate);
            DateTime.TryParseExact(Request.Form[departureDate.UniqueID], "dd.MM.yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out this.postDepartureDate);
            Int32.TryParse(Request[this.ddlPeoplesCount.UniqueID], out this.postNumberOfPeople);

        }

        private void RedirectIfValid() {
            if (this.postArrivalDate > DateTime.MinValue
                && this.postArrivalDate < this.postDepartureDate
                && this.postNumberOfPeople > 0
                && this.postNumberOfPeople <= this.PeoplesCount) {
                SearchState newState = SearchState.GetState(this.postArrivalDate, this.postDepartureDate, this.postNumberOfPeople);
                NavigationProvider navi = NavigationProvider.Instance();
                string url = navi.GetUrl(newState);
                Response.Redirect(url, true);
                //string urlName = GetGlobalResourceObject("Aparts", "apartmentsUrl").ToString();
                //SiteCity sc = Factory.Instance().GetSiteCity();
                //if (sc != null)
                //    urlName = urlName + "-" + sc.DefaultName;
                //Response.Redirect(UrlUtils.GetReservationUrl(Factory.Instance().GetPreFolderEvaluation(), postArrivalDate, postDepartureDate, this.postNumberOfPeople, 0, urlName), true);
            }
        }

        #endregion

    }
}